package com.yinhe.music.yhmusic.localmusic.view;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.hwangjr.rxbus.RxBus;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.adapter.MoreDialogAdapter;
import com.yinhe.music.yhmusic.base.BasePresenter;
import com.yinhe.music.yhmusic.base.BaseServiceDialogFragment;
import com.yinhe.music.yhmusic.cache.CacheManager;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.db.DataBaseAccessor;
import com.yinhe.music.yhmusic.dialog.collect.CollectionDialog;
import com.yinhe.music.yhmusic.login.LoginRegisterActivity;
import com.yinhe.music.yhmusic.model.MoreBean;
import com.yinhe.music.yhmusic.model.Music;
import com.yinhe.music.yhmusic.utils.MusicUtils;
import com.yinhe.music.yhmusic.utils.Preferences;
import com.yinhe.music.yhmusic.utils.SongUtil;
import com.yinhe.music.yhmusic.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 何晓华 on 2018/3/15.
 */

public class LocalMusicDialog extends BaseServiceDialogFragment {
    private static final int[] icon = {R.drawable.ic_more_add, R.drawable.ic_next_play, R.drawable.ic_more_delete};
    private static final String[] iconName = {"添加到", "下一首", "删除"};
    Context mContext;
    TextView moreName;
    RecyclerView recyclerView;
    MoreDialogAdapter dialogAdapter;
    Music music;
    String menuId;
    /**
     * 更多菜单来源 SONG_MENU_MANAGER/RECENT_PLAY_MANAGER/LOCAL_MUSIC
     */
    int type;
    int id;


    public static LocalMusicDialog newInstance(Music music, int type, String menuId) {

        Bundle args = new Bundle();
        args.putSerializable("music", music);
        args.putInt("type", type);
        args.putString("menuid", menuId);

        LocalMusicDialog fragment = new LocalMusicDialog();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_FRAME, R.style.CustomDatePickerDialog);
        RxBus.get().register(this);
        mContext = getContext();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        initWindows();
        View view  = inflater.inflate(R.layout.fragment_music_more, container);
        moreName = view.findViewById(R.id.more_name);
        recyclerView = view.findViewById(R.id.new_more_recyclerView);
        view.findViewById(R.id.cancel).setOnClickListener(view1 -> dismiss());
        if (getArguments() != null) {
            music  = (Music) getArguments().getSerializable("music");
            menuId = getArguments().getString("menuid");
            type   = getArguments().getInt("type",IConstants.LOCAL_MUSIC);
        }
        initMoreList();
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        if (window != null) {
            window.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT);
        }
        getDialog().setCanceledOnTouchOutside(true);
    }

    private void initWindows() {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        WindowManager.LayoutParams params = getDialog().getWindow().getAttributes();
        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setAttributes(params);
    }

    private void initMoreList() {
        List<MoreBean> data = new ArrayList<>();
        for (int i = 0; i < icon.length; i++) {
            MoreBean moreBean = new MoreBean(iconName[i], icon[i]);
            data.add(moreBean);
        }

        recyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));
        dialogAdapter = new MoreDialogAdapter(data);
        recyclerView.setAdapter(dialogAdapter);
        recyclerView.setHasFixedSize(true);
        moreName.setText(music.getSongName());

        setItemClick();
    }

    private void setItemClick() {
        dialogAdapter.setOnItemClickListener((adapter, view1, position) -> {
            switch (position) {
                case 0:
                    if (Preferences.getLoginSn().isEmpty()) {
                        mContext.startActivity(new Intent(mContext, LoginRegisterActivity.class));
                    } else {
                        ArrayList<Integer> idList = new ArrayList<>();
                        idList.add((int) music.getSongId());
                        CollectionDialog collectionDialog = CollectionDialog.newInstance(idList, IConstants.LOCAL);
                        collectionDialog.show(getFragmentManager(), "CollectionDialog");
                    }
                    dismiss();
                    break;
                case 1:
                    if (mService != null) {
                        mService.addMusicToPlayList(music, mService.getPlayingPosition());
                        ToastUtils.show(R.string.add_playlist_next_play);
                    }
                    dismiss();
                    break;
                case 2:
                    if (menuId != null) {
                        id = Integer.parseInt(menuId);
                    }
                    deleteMusic(music, id);
                    dismiss();
                    break;
                default:
                    break;
            }
        });
    }

    private void deleteMusic(Music music, int menuId) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
        dialog.setTitle("确定将所选音乐从列表中删除？");
        dialog.setPositiveButton("确定", (dialog1, which) -> {
            if (type == IConstants.SONG_MENU_MANAGER) {
                SongUtil.removeSong((int) music.getSongId(), menuId);
            } else if (type == IConstants.RECENT_PLAY_MANAGER) {
                List<Integer> idList = new ArrayList<>();
                idList.add((int) music.getSongId());
                DataBaseAccessor.getInstance().deleteRecentSongList(idList);
            } else if (type == IConstants.LOCAL_MUSIC) {
                List<Music> musicList = new ArrayList<>();
                musicList.add(music);
                MusicUtils.deleteLocalMusic(mContext, musicList);
                CacheManager.getInstance().deleteScanMusic(music);
            }
        });
        dialog.setNegativeButton("取消", null);
        dialog.show();
    }

    @Override
    public BasePresenter getPresenter() {
        return null;
    }

    @Override
    public void initPresenter() {

    }
}
